<?php

namespace app\admin\middleware;

use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\common\Error;
use think\facade\View;

class CheckAdminAuth
{
    public function handle($request, \Closure $next)
    {
        $userId = Session::get('user_id');
        $ruleId = Session::get('rule_id');

        if (empty($ruleId) || empty($userId)) {
            return redirect(url('admin/login/index'));
            // return json(['code' => Error::NOT_LOGGED_CODE, 'message' => Error::PLEASE_LOGIN_FIRST]);
        }

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.admin.admin_menu_data');

        $authUrl = $redis->get($key . $ruleId);
        if (!$authUrl) {
            return redirect(url('admin/login/index'));
            // return json(['code' => Error::NOT_LOGGED_CODE, 'message' => Error::PLEASE_LOGIN_FIRST]);
        }

        $authArrayUrl = json_decode($authUrl, true);

        $requestUrl = 'admin/' . Request::controller() . '/' . Request::action();
        $url = strtolower($requestUrl);

//不验证路由
        $notAuthRequestUrl = ['admin/localvideos/download','admin/weibotitel/download','admin/admin/select','admin/actionlog/index','admin/actionlog/list','admin/localvideos/allemploy','admin/localvideos/allemploydy','admin/localvideos/allemploywb','admin/localvideos/allreject','admin/admin/upload','admin/titelhot/editimginfo','admin/titelhot/editinfo','admin/titelhot/content1','admin/titelhot/content'];


        if (!in_array($url, $notAuthRequestUrl)) {
            if ($ruleId !== 1) {
                if (!in_array($url, $authArrayUrl)) {
                    return json(['code' => Error::NOT_REQUEST_AUTH_CODE, 'message' => Error::NOT_REQUEST_AUTH_MESSAGE]);
                }

            }

        }


        return $next($request);
    }
}